package com.lam.mall.service.impl;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lam.common.constant.CommonConstant;
import com.lam.common.exception.ParameterErrorException;
import com.lam.common.utils.CollectionUtil;
import com.lam.common.utils.NumberUtil;
import com.lam.common.utils.StringUtils;
import com.lam.mall.entity.TransFeeItem;
import com.lam.mall.entity.TransFeeTemplate;
import com.lam.mall.entity.TransFree;
import com.lam.mall.mapper.TransFeeTemplateMapper;
import com.lam.mall.param.TransFeeTemplateParam;
import com.lam.mall.service.TransFeeItemService;
import com.lam.mall.service.TransFeeTemplateService;
import com.lam.mall.service.TransFreeService;

/**
 * 运费模板Service业务层处理
 * 
 * @author admin
 * @date 2023-04-21
 */
@Service
public class TransFeeTemplateServiceImpl  implements TransFeeTemplateService {

    @Autowired
    private TransFeeTemplateMapper transFeeTemplateMapper;
    @Autowired
    private TransFeeItemService transFeeItemService;
    @Autowired
    private TransFreeService transFreeService;

    @Override
	@CacheEvict(cacheNames = "TransFeeTemplateItems", key = "#id")
	public void removeTransFeeTemplateItemsCache(String id) {
	}
    
    /**
     * 查询运费模板
     * 
     * @param id ID
     * @return 单个对象
     */
    @Cacheable(cacheNames = "TransFeeTemplateItems", key = "#id")
    @Override
    @Transactional(readOnly = true)
    public TransFeeTemplate selectByIdCache(String id) {

        return selectById(id);
    }
    
    @Override
    @Transactional(readOnly = true)
    public TransFeeTemplate selectById(String id) {

    	TransFeeTemplate transFeeTemplate = transFeeTemplateMapper.selectById(id);
    	if(transFeeTemplate != null) {
    		transFeeTemplate.setTransFeeItemList(transFeeItemService.selectByTemplateId(id));
    		if(NumberUtil.eq(transFeeTemplate.getHasFreeCondition(), CommonConstant.YES1)) {
    			transFeeTemplate.setTransFreeList(transFreeService.selectByTemplateId(id));
    		}
    	}
        return transFeeTemplate;
    }

    /**
     * 查询运费模板列表
     * 
     * @param param
     * @return 
     */
    @Override
    @Transactional(readOnly = true)
    public List<TransFeeTemplate> selectList(TransFeeTemplateParam param) {
    
        QueryWrapper<TransFeeTemplate> queryWrapper = new QueryWrapper<>();

        //关键字查询
        if(StringUtils.isNotBlank(param.getKeywords())) {
            queryWrapper.and(wr->{
                wr.or().like("template_name", param.getKeywords());
            });
        }
        
        queryWrapper.like(StringUtils.isNotBlank(param.getTemplateNameKey()), "template_name", param.getTemplateNameKey());
        queryWrapper.eq(StringUtils.isNotBlank(param.getTemplateName()), "template_name", param.getTemplateName());
        queryWrapper.eq(Objects.nonNull(param.getShopId()), "shop_id", param.getShopId());
        queryWrapper.eq(Objects.nonNull(param.getChargeType()), "charge_type", param.getChargeType());
        queryWrapper.eq(Objects.nonNull(param.getIsFreeFee()), "is_free_fee", param.getIsFreeFee());
        queryWrapper.eq(Objects.nonNull(param.getHasFreeCondition()), "has_free_condition", param.getHasFreeCondition());

        return transFeeTemplateMapper.selectList(queryWrapper);
    }

    /**
     * 新增运费模板
     * 
     * @param transFeeTemplate 
     * @return 
     */
    @Override
    @Transactional
    public int insert(TransFeeTemplate transFeeTemplate) {
    
    	// 插入运费模板
    	transFeeTemplateMapper.insert(transFeeTemplate);
    	
    	// 插入所有的指定包邮条件项和城市
		if (NumberUtil.eq(transFeeTemplate.getHasFreeCondition(), CommonConstant.YES1)) {
			insertTransFree(transFeeTemplate);
		}
    			
		// 插入所有的运费项和城市
    	insertTransFeeItem(transFeeTemplate);

        return 1;
    }
    
    private void insertTransFeeItem(TransFeeTemplate transFeeTemplate) {
		List<TransFeeItem> transFeeList = transFeeTemplate.getTransFeeItemList();
		for (TransFeeItem transFeeItem : transFeeList) {
			transFeeItem.setTransFeeTemplateId(transFeeTemplate.getId());
			transFeeItemService.insert(transFeeItem);
		}
	}

    private void insertTransFree(TransFeeTemplate transFeeTemplate) {
		List<TransFree> transFreeList = transFeeTemplate.getTransFreeList();
		for (TransFree transFree : transFreeList) {
			transFree.setTransFeeTemplateId(transFeeTemplate.getId());
			transFreeService.insert(transFree);
		}
	}
    
    /**
     * 修改运费模板
     * 
     * @param transFeeTemplate 
     * @return 
     */
    @Override
    @Transactional
    public int update(TransFeeTemplate transFeeTemplate) {
    
    	TransFeeTemplate transFeeTemplateDb = selectById(transFeeTemplate.getId());
    	deleteSubItems(transFeeTemplateDb);
    	
    	// 更新运费模板
    	transFeeTemplateMapper.updateById(transFeeTemplate);
    	
    	// 插入所有的指定包邮条件项和城市
		if (NumberUtil.eq(transFeeTemplate.getHasFreeCondition(), CommonConstant.YES1)) {
			insertTransFree(transFeeTemplate);
		}
		
		// 插入所有的运费项和城市
    	insertTransFeeItem(transFeeTemplate);

        return 1;
    }

    /**
     * 删除运费模板信息
     * 
     * @param idStr ID，多个用逗号分隔
     * @return 
     */
    @Override
    @Transactional
    public int deleteById(String idStr) {
    
        if(StringUtils.isBlank(idStr)) {
            return 0;
        }
        List<String> ids = StringUtils.str2List(idStr);
        for (String id : ids) {
			TransFeeTemplate transFeeTemplate = selectById(id);
			if(transFeeTemplate == null) {
				throw new ParameterErrorException(String.format("运费模板不存在(%s)", id));
			}
			
			deleteSubItems(transFeeTemplate);
		}
        return transFeeTemplateMapper.deleteBatchIds(ids);
    }

	private void deleteSubItems(TransFeeTemplate transFeeTemplate) {
		List<TransFeeItem> transFeeItemList = transFeeTemplate.getTransFeeItemList();
		if(CollectionUtil.isNotEmpty(transFeeItemList)) {
			// 删除所有的运费项和其包含的城市
			transFeeItemService.deleteById(transFeeItemList.stream().map(TransFeeItem::getId).collect(Collectors.toList()));
		}
		
		List<TransFree> transFreeList = transFeeTemplate.getTransFreeList();
		if(CollectionUtil.isNotEmpty(transFreeList)) {
			//删除所有指定包邮条件项和城市
			transFreeService.deleteById(transFreeList.stream().map(TransFree::getId).collect(Collectors.toList()));
		}
	}

}
